﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class ManagerViewmodel : ViewmodelBase
    {
        public ManagerViewmodel()
        {
            ManagerClient.GetAllManagerCompleted += GetAllManagerCompleted;
            ManagerClient.InsertManagerCompleted += InsertManagerCompleted;
            ManagerClient.UpdateStatusCompleted += UpdateStatusCompleted;
            ManagerClient.GetAllRoleCompleted += GetAllRoleCompleted;
            ManagerClient.GetManagerInfoCompleted+=GetManagerInfoCompleted;
            if (DataContext.IsValid)
            {
                LoadData();
            }
        }

        #region Methods
        private void GetManagerInfoCompleted(object sender, DataService.GetManagerInfoCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                
            }
        }

        private void GetAllRoleCompleted(object sender, DataService.GetAllRoleCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    RolesCollection = new ObservableCollection<RoleInfo>(e.Result.Entities.OfType<RoleInfo>());
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void UpdateStatusCompleted(object sender, DataService.UpdateStatusCompletedEventArgs e)
        {
            LoadData();
        }

        private void InsertManagerCompleted(object sender, DataService.InsertManagerCompletedEventArgs e)
        {
            Operation = EntityOperation.None;
            UpdateEntity = new ManagerInfo();
            LoadData();
        }

        private void GetAllManagerCompleted(object sender, DataService.GetAllManagerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    ItemsCollection = new ObservableCollection<DataObjectInfo>(e.Result.DataObjects);
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            IsBusy = false;
            ManagerClient.GetAllRoleAsync(Account, Password);
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            ManagerClient.GetAllManagerAsync(Account, Password);
        }
        #endregion

        #region Properties

        private ObservableCollection<DataObjectInfo> _itemsCollection;
        public ObservableCollection<DataObjectInfo> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
                RaisePropertyChanged(() => DisplayCollection);
            }
        }

        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
                RaisePropertyChanged(() => DisplayCollection);
            }
        }

        private string _confirmPassword = string.Empty;
        public string ConfirmPassword
        {
            get
            {
                return _confirmPassword;
            }
            set
            {
                _confirmPassword = value;
                RaisePropertyChanged(() => ConfirmPassword);
                RaisePropertyChanged(() => MatchPassword);
            }
        }

        public bool MatchPassword
        {
            get
            {
                if (UpdateEntity == null || string.IsNullOrEmpty(UpdateEntity.Password))
                {
                    return true;
                }
                return UpdateEntity.Password == ConfirmPassword;
            }
        }

        public IEnumerable<object> DisplayCollection
        {
            get
            {
                if (ItemsCollection == null)
                {
                    return null;
                }
                var items = (from t in ItemsCollection
                             select new
                             {
                                 Id = t["Id"],
                                 Name = (string)t["Name"],
                                 Account = (string)t["Account"],
                                 RegisterTime = (DateTime)t["RegisterTime"],
                                 Role = t["Role"],
                                 AccountStatus = (AccountStatusValue)Convert.ToInt32(t["AccountStatus"])
                             }).Where(t => t.Account.Contains(Keywords) || t.Name.Contains(Keywords));
                return items;
            }
        }

        private ObservableCollection<RoleInfo> _rolesCollection;
        public ObservableCollection<RoleInfo> RolesCollection
        {
            get { return _rolesCollection; }
            set
            {
                _rolesCollection = value;
                RaisePropertyChanged(() => RolesCollection);
            }
        }
        #endregion

        #region Update
        private ManagerInfo _updateEntity = new ManagerInfo();
        public ManagerInfo UpdateEntity
        {
            get { return _updateEntity; }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
            }
        }

        private RoleInfo _selectedRole;
        public RoleInfo SelectedRole
        {
            get { return _selectedRole; }
            set
            {
                _selectedRole = value;
                RaisePropertyChanged(() => SelectedRole);
                if (SelectedRole != null)
                {
                    UpdateEntity.RoleId = SelectedRole.Id;
                }
                RaisePropertyChanged(() => SubmitCommand);
            }
        }
        #endregion

        #region Commands
        public ICommand BlockCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    if (id != DataContext.CurrentAccount.Id)
                    {
                        ManagerClient.UpdateStatusAsync(Account, Password, id, AccountStatusValue.Block);
                    }
                });
            }
        }

        public ICommand UnblockCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    ManagerClient.UpdateStatusAsync(Account, Password, id, AccountStatusValue.Normal);
                });
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    ManagerClient.UpdateStatusAsync(Account, Password, id, AccountStatusValue.Removed);
                });
            }
        }

        public ICommand InsertCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        UpdateEntity = new ManagerInfo();
                        Operation = EntityOperation.Insert;
                    }
                };
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return SelectedRole != null; },
                    ExecuteCallback = delegate
                    {
                        ManagerClient.InsertManagerAsync(Account, Password, UpdateEntity.Account, UpdateEntity.Password, UpdateEntity.Name, UpdateEntity.Mobile, UpdateEntity.Email, UpdateEntity.RoleId);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Operation = EntityOperation.None;
                        UpdateEntity = new ManagerInfo();
                    }
                };
            }
        }
        #endregion
    }
}
